package linuxbox.common.taglib;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.util.*;
import java.io.*;

public class Iteration extends BodyTagSupport
{
  private String name, type;
  private Iterator iterator;

  public void setName(String name)
  {
    this.name = name;
  }

  public void setType(String type)
  {
    this.type = type;
  }

  public void setGroup(Iterator it)
  {
    if (it.hasNext())
      iterator = it;
  }

  public int doStartTag()
  {
    if(iterator == null)
      return SKIP_BODY;
    if(iterator.hasNext())
    {
      pageContext.setAttribute(name, iterator.next());
      return EVAL_BODY_BUFFERED;
    }
    else
    {
      return SKIP_BODY;
    }
  }

  public int doAfterBody() throws JspException
  {
    BodyContent body = getBodyContent();
    try
    {
      body.writeOut(getPreviousOut());
    }
    catch (IOException e)
    {
      throw new JspTagException("IterationTag: " + e.getMessage());
    }
      // clear up so the next time the body content is empty
    body.clearBody();
    if (iterator.hasNext())
    {
      pageContext.setAttribute(name, iterator.next());
      return EVAL_BODY_BUFFERED;
    }
    else
    {
      return SKIP_BODY;
    }
  }
}
